import { createStore } from "redux";

const initState = {
  car: JSON.parse(localStorage.getItem('car')) || [],
};
const rootReducer = (prevState = initState, action) => {
  const { type, payload } = action
  if (type === "setCar") {
    return {
      ...prevState,
      car: payload,
    };
  }
  if(type === 'clearCar') {
    return {
      ...prevState,
      car: []
    }
  } 
  if(type === 'delCar') {
    return {
      ...prevState,
      car: prevState.car.filter(v => v.id !== payload.id)
    }
  }

  if(type === 'changeState') {
    const item = prevState.car.find(v => v.id === payload.id);
    if(item) item.state = !item.state
    return {
      ...prevState,
      car: [...prevState.car]
    } 
  }
  return prevState;
};

const store = createStore(rootReducer);

store.subscribe(() => {
  const state = store.getState();
  localStorage.setItem('car', JSON.stringify(state.car))
})
export default store;
